//
//  SydenyAppDelegate.m
//  Sydeny
//
//  Created by Rainbow on 7/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SydenyAppDelegate.h"
#import "ServiceHelper.h"
#import "CacheData.h"

@implementation UINavigationBar (CustomImage)  
- (void)drawRect:(CGRect)rect {  
    UIImage *image = [UIImage imageNamed: @"topbar.png"];  
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  
}  
@end

@implementation SydenyAppDelegate

@synthesize window=_window;
@synthesize tabbarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [self initData];
    [self.window makeKeyAndVisible];
    
    UINavigationBar *navigationBar = [[UINavigationBar alloc] init];
    if ([navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        
        [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"topbar_320.png"] forBarMetrics:UIBarMetricsDefault];
    }
    [navigationBar release];
    return YES;
}

-(void)initData
{
    
    loadCoverView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default@2x.png"]];
    loadCoverView.frame = CGRectMake(0, 0, 320, 480);
    [self.window addSubview:loadCoverView];
    if (![[ServiceHelper sharedService] checkNetwork:@"无网络连接！"]) {
        return;   
    }
    [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestGetAdvertising WithParameters:nil AndCallBackScope:self AndSuccessSel:@"getAdSuccess:" AndFailedSel:@"getAdFailed:"];
    
    locationManager = [[CLLocationManager alloc] init];
    if (!locationManager.locationServicesEnabled)
    {
        NSLog(@"User has opted out of location services");
    }
    
    else
    {
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        locationManager.distanceFilter = 5.0f; // in meters
        [locationManager startUpdatingLocation];
    }
    
    if ([[NSUserDefaults standardUserDefaults] stringForKey:DEVICE_TOKEN] == nil || [@"" isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:DEVICE_TOKEN]]) {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
    }

}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	NSLog(@"Location manager error: %@",[error description]);
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
	NSLog(@"Reverse geocoder error: %@",[error description]);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
	CLLocationCoordinate2D location2D = newLocation.coordinate;
	[locationManager stopUpdatingLocation];
    [CacheData sharedData].latitude = [NSString stringWithFormat:@"%f",location2D.latitude];
    [CacheData sharedData].longitude = [NSString stringWithFormat:@"%f",location2D.longitude];
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    
}



- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
    [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestGetAdvertising WithParameters:nil AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:NN_ENTER_FOREGROUND object:nil];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken 
{   
    
	NSString *str = [devToken description]; 
    str = [str substringWithRange:NSMakeRange(1, 71)];
    str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:US_PUSH_NOTIFICATION];
	[[NSUserDefaults standardUserDefaults] setObject:str forKey:DEVICE_TOKEN];
	[[NSUserDefaults standardUserDefaults] synchronize];	
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:0];
    [params setObject:@"1" forKey:@"state"];
    [params setObject:str forKey:@"token"];
    [[ServiceHelper sharedService] requestServerForMethod:SydenyRequestSetNotification WithParameters:params AndCallBackScope:nil AndSuccessSel:nil AndFailedSel:nil];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {     
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:US_PUSH_NOTIFICATION];
    NSLog(@"Error in registration. Error: %@", err);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
//    [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber + [[userInfo objectForKey:@"badge"] intValue];
//    
}

-(void)getAdSuccess:(NSObject *)result
{
    [self.window addSubview:tabbarController.view];
}

-(void)getAdFailed:(NSObject *)result
{
    
}

-(void)removeCoverView
{
    if (loadCoverView != nil) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDelay:1.0f];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(coverHideStop)];
        loadCoverView.alpha = 0;
        [UIView commitAnimations];
    }
}

-(void)coverHideStop
{
    [loadCoverView removeFromSuperview];
    [loadCoverView release];
    loadCoverView = nil;
}

- (void)dealloc
{
    [_window release];
    [tabbarController release];
    [locationManager release];
    [super dealloc];
}

@end
